using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;

namespace OCAP_FACAEmail_Api.AppCode
{
    public class CommUtil
    { 
        public static string getJobVal(JToken jtk, string propertyname, HashSet<string> addlists = null, bool nullWrong = false)
        {
            string res = null;
            var value = jtk?[propertyname]?.ToString()?.Trim();

            if (value is null)
            {
                if (nullWrong)
                {
                    throw new Exception($"{propertyname} not exist");
                }
                else
                {
                    //无操作
                }
            }
            else
            {
                res = value;
                //有值才添加
                if (addlists != null)
                {
                    addlists.Add(propertyname);
                }
            }

            //jtk为空时
            if ((jtk is null) && (addlists != null))
            {
                addlists.Add(propertyname);
            }


            return res ?? string.Empty;
        }
    }


    public static class ExtendMethod
    {
        public static int ToInt32(this string s)
        {
            if (int.TryParse(s, out int i))
                return i;
            else
                return 0;
        }

        public static long ToInt64(this string s)
        {
            if (long.TryParse(s, out long i))
                return i;
            else
                return 0;
        }

        public static DateTime ToDateTime(this string dtTime)
        {
            if (DateTime.TryParse(dtTime, out DateTime i))
                return i;
            else
                return DateTime.Now;
        }

        public static double ToDouble(this string s)
        {
            if (double.TryParse(s, out double i))
                return i;
            else
                return 0.0;
        }

        //时间转成时间戳
        public static Int64 ToInt64(this DateTime time)
        {
            TimeSpan ts = time - TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1, 0, 0, 0, 0),TimeZoneInfo.Local);
            var timestamp = Convert.ToInt64(ts.TotalMilliseconds);
            return timestamp;
        }
        
        // 从逗号分隔的字符串中移除指定的ID
        public static string DelIdFromString(this string StringIDs,string delID)
        {
            if (string.IsNullOrEmpty(StringIDs))
            {
                return string.Empty;
            }
            try
            {
                return string.Join(",",
                    StringIDs.Split(',')
                        .Select(s => int.Parse(s.Trim()))
                        .Where(num => num != int.Parse(delID.Trim()))
                );
            }
            catch (FormatException)
            {
                return "error";
            }
        }

    }
}